<template>
  <div class="xtx-goods-page">
    <div class="container" v-if="loading">
      <div class="loading"></div>
    </div>
    <div class="container" v-else>
      <XtxBread>
        <XtxBreadItem to="/">首页</XtxBreadItem>
        <XtxBreadItem :to="`/category/${goods.categories[1].id}`">
          {{ goods.categories[1].name }}
        </XtxBreadItem>
        <XtxBreadItem>{{ goods.name }}</XtxBreadItem>
      </XtxBread>
      <!-- 商品容器 -->
      <div class="goods-wrapper">
        <div class="media">
          <!-- 图片预览组件 -->
          <XtxImageView :images="goods.mainPictures"></XtxImageView>
          <!-- 商品销售统计 -->
          <GoodsSales />
        </div>
        <div class="spec">
          <!-- 商品信息 -->
          <GoodsInfo :goods="goods" />
          <!-- SKU组件（选完规格之后得到SKUID和其他关联信息 价格 库存 ...） -->
          <XtxSku :goods="goods" @change="changeSku" />
          <!-- 数量组件 -->
          <XtxNumbox :min="1" v-model="count" label="数量" />
          <!-- 按钮 -->
          <XtxButton @click="insertCart" type="primary" style="margin-top: 20px; margin-left: 60px">
            加入购物车
          </XtxButton>
        </div>
      </div>
      <!-- 商品底部 -->
      <GoodsFooter :goods="goods" />
    </div>
  </div>
</template>

<script>
import { onMounted, ref } from 'vue'
import { getGoods } from '@/api/goods'
import { onBeforeRouteUpdate, useRoute } from 'vue-router'
import GoodsInfo from './components/goods-info.vue'
import GoodsSales from './components/goods-sales.vue'
import GoodsFooter from './components/goods-footer.vue'

import Message from 'erabbit-ui/packages/components/Message'
import { useStore } from 'vuex'

export default {
  name: 'xtx-goods-page',
  components: { GoodsInfo, GoodsSales, GoodsFooter },
  setup() {
    // 1. 获取数据渲染面包屑
    // 1.1 定义API函数
    // 1.2 组件初始化的时候获取数据
    // 1.3 加载中效果
    // 1.4 商品ID参数改变重新更新
    // null 注意：模板中没有数据前，不要去访问goods中的数据，null.name 报错
    // {} 容错好一些，{}.name 访问数据，至少不会报错
    const goods = ref(null)

    // 默认就是没有数据，加载中
    const loading = ref(true)

    const loadData = async id => {
      loading.value = true
      const data = await getGoods(id)
      goods.value = data.result
      loading.value = false
    }

    const route = useRoute()
    onMounted(() => {
      loadData(route.params.id)
    })

    onBeforeRouteUpdate((to, from, next) => {
      loadData(to.params.id)
      next()
    })

    // sku信息改变
    const currSku = ref(null)
    const changeSku = ret => {
      // console.log(ret)
      if (ret.skuId) {
        // 更新商品展示信息
        goods.value.price = ret.price
        goods.value.oldPrice = ret.oldPrice
        goods.value.inventory = ret.inventory
        count.value = 1
        currSku.value = ret
      } else {
        currSku.value = null
      }
    }

    const count = ref(1)

    // 加入购物车
    // 1. 约定存储购物车信息的字段（和后台给的一致）
    // 2. 定义 mutations 函数
    // 3. 定义 actions 函数 （判断登录状态）
    // 4. 商品详情组件，加入购物车操作
    // 5. sku信息需要，商品库存合理，组织数据，调用actions即可

    // 购物车商品信息对象：
    // {id,name,picture,count,skuId,attrsText,selected,nowPrice,price,stock,isEffective}
    const store = useStore()
    const insertCart = () => {
      if (!currSku.value) return Message({ text: '请选择商品规格' })
      if (count.value > goods.value.inventory) return Message({ text: '库存不足' })
      store
        .dispatch('cart/insertCart', {
          id: goods.value.id,
          name: goods.value.name,
          picture: goods.value.mainPictures[0],
          count: count.value,
          skuId: currSku.value.skuId,
          attrsText: currSku.value.specsText,
          selected: true,
          nowPrice: currSku.value.price,
          price: currSku.value.price,
          stock: currSku.value.inventory,
          isEffective: true
        })
        .then(() => {
          Message({ text: '加入购物车成功', type: 'success' })
        })
        .catch(() => {
          Message({ text: '加入购物车失败', type: 'error' })
        })
    }

    return { goods, loading, changeSku, count, insertCart }
  }
}
</script>

<style lang="less" scoped>
.loading {
  height: 600px;
  border-top: 72px solid #f5f5f5;
  background: #fff url(../../assets/load.gif) no-repeat center / 80px 80px;
}
.goods-wrapper {
  display: flex;
  background: #fff;
  padding: 40px;
  .media {
    width: 480px;
    margin-right: 40px;
  }
}
</style>